<?php

class Login extends Model {
	
	function Login()
	{
		parent::Model();
	}
	/*
	 * Authentcates every user's login
	 * $table -> indicates where table to fetch the details
	 * $username -> indicates a user's email
	 * $password -> indicates a user's password
	 * $salt -> fetches the user's salt (a randaom string generated)
	 */
	function authenticate($table, $username, $password, $salt){
		$this->db->from($table);
		$this->db->where('email', $username);
		$this->db->where('salt', $salt);
		$this->db->where('password', sha1($salt.$password));
		$this->db->where('status', 'approved');
		$query = $this->db->get();
		
		if(sizeof($query->row_array())>0)
		{
			return true;
		}
		return false;
	}
	/*
	 * Fetches the salt of a user.
	 * $email -> indicates the email of a user.
	 */
	function getSalt($email){
		$this->db->select('salt');
		$this->db->from('user');
		$this->db->where('email', $email);
		$query = $this->db->get()->row_array();
		return $query['salt'];
	}
	
	function fetch($table, $username, $password, $salt){
		$this->db->from($table);
		$this->db->where('email', $username);
		$this->db->where('salt', $salt);
		$this->db->where('password', sha1($salt.$password));
		$this->db->where('status', 'approved');
		$query = $this->db->get();
		return $query->row_array();
	}

	/*
	 * This fetches the newly saved updates
	 * $user_id -> indicates the session id userdata of the user.
	 * $table -> indicates where table to fetch the data
	 */
	function refresh($table, $id){
		$this->db->from($table);
		$this->db->where('user_id', $id);
		$query = $this->db->get();
		return $query->row_array();
	}
	
	/*
	 * Fetches the last_login time of a user
	 * $table -> indicates where table to fetch the data
	 * $email -> indicates the email of a user.
	 */
	function last_login($table, $email){
		$date = date('Y-m-d H:i:s', now());
		$data = array('last_login' => $date);

		$this->db->where('email', $email);
		$this->db->update('user', $data);
	}

	/*
	 * Fetches the pending users in the DB
	 * $username -> indicates a user's email
	 */
	function isPending($table, $username){
		$this->db->from($table);
		$this->db->where('email', $username);
		$this->db->where('status', 'pending');	
		$query = $this->db->get();
		if(sizeof($query->row_array())>0)
		{
			return true;
		}
		return false;
	}
}
?>
